package com.mofang.ticketing.common.security.component;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Map;

/**
 * 动态权限数据源，用于获取动态权限规则
 *
 * @author LGC
 */
public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private DynamicSecurityService dynamicSecurityService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        Map<String, Collection<ConfigAttribute>> configAttributeMap = dynamicSecurityService.loadDataSource();
        //获取当前访问的路径 object 中包含用户请求的request 信息
        HttpServletRequest request = ((FilterInvocation) o).getHttpRequest();
        //获取访问该路径所需资源角色
        for (String url : configAttributeMap.keySet()) {
            if (new AntPathRequestMatcher(url).matches(request)) {
                return configAttributeMap.get(url);
            }
        }
        // 未设置操作请求权限，返回空集合
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

}
